@import("js.annot");

const {eventFieldTransfer} = require("../library/transfer.js");

const uiFolder = @.fs.realOSPath(__dirname, "..", "..", "..", "ui");


var events = {};
var eventConfigUpgradeTimeout = null;

@annot.func("mewchan.kitty", "slime.event", function({name, alias, trigger, fields = {}}) {

    if (!name) {
        throw @lab.errors.invalid_parameters;
    }

    var kitty = @kitty(this.file);
    var kittyName = kitty.name.split(".")[0];

    if (@.is.nil(events[kittyName])) {
        events[kittyName] = {
            events: {}
        }
    }

    

    if (events[kittyName].events[name]) {
        return @.async.resolve();
    } else {
        events[kittyName].events[name] = {
            group : kittyName,
            name, alias,
            fields
        };

        var result = {};
        
        result[kittyName + "_" + name + "_events"] = @.merge.simple({
            "id": @lab.types.id(),
            "ouid": @lab.types.indexed_string(),
            "member_id": @lab.types.indexed_string(),
            "event_source": @lab.types.indexed_string(),
            "source_event_id": @lab.types.indexed_string(),
            "source_event_date": @lab.types.date(),
            "create_date": @lab.types.date(),
        }, fields ? eventFieldTransfer(fields) : {});


        if (eventConfigUpgradeTimeout) {
            clearTimeout(eventConfigUpgradeTimeout)
        }

        eventConfigUpgradeTimeout = setTimeout(function() {

            var libraryFolder = @.fs.realOSPath(uiFolder, "src", "store", "modules", "elasticsearch_crm", "library");
            var eventsFileContent = "export default " + JSON.stringify(events, null, 2).replace(/\"/g, "'") + "\n";
            return @.fs.writeFile(@.fs.realOSPath(libraryFolder, "events.js"), eventsFileContent).then(async function () {
                @mew.auto("slime.event_updated",events);
            })

        }, 1000);

        if (trigger) {
            @heard(trigger).then(function (mew) {
                var {member} = mew.content[mew.usage];
                @lab(function (lab) {
                    return lab.slime.member.@createEvent({
                        group : kittyName,
                        event : name,
                        ouid : member.ouid,
                        member_id : member.id,
                    });
                }).rejected(@error);
            });
        }
        
        return @lab.export.model(result).then(async function () {
            @mew.auto("slime.event_registered",{
                event : events[kittyName].events[name]
            });
        });
    }
})

module.exports = events;